using System;
using System.Drawing;
using System.Windows.Forms;



// Spectrum Analyzer bars
public class Spectrum:Control
{
	private Bitmap	bufferBitmap;
	private Color	c_back;
	private Color	c_bars;
	private SolidBrush b_back;
	private SolidBrush b_bars;
	private Pen			p_bars;
	private float[] spec;
	private int i=0;
	private int xPos=0;
	private int height;
	private int MaxValue=0;
	private int NumBars = 16;
	private int xBarSize = 1;

	/// <summary>
	/// Initialize Spectrum analyzer control
	/// </summary>
	/// <param name="dimensions">Dimensions of our control</param>
	/// <param name="bars">Bars color</param>
	/// <param name="back">Background color</param>
	/// <param name="num_bars">Number of bars (the more bars: more nice and more slow :D)</param>
	/// <param name="maxValue">Maximum value of the bars</param>
	public Spectrum (Rectangle dimensions, Color bars, Color back, int numBars, int maxValue):base()
	{
		c_bars = new Color();
		c_back = new Color();
		spec = new float[32];
		MaxValue = maxValue;
		NumBars = numBars;

		xBarSize = dimensions.Width/numBars;
		this.Bounds = dimensions;
		c_back = back;
		c_bars = bars;
		b_back = new SolidBrush(c_back);
		b_bars = new SolidBrush(c_bars);

		p_bars = new Pen(c_bars);
		bufferBitmap = new Bitmap (this.Bounds.Width, this.Bounds.Height);
	}

	public Color BarsColor
	{
		get {return c_bars; }
		set
		{
			c_bars = value;
			Invalidate();
		}
	}
	public Color FonsColor
	{
		get {return c_back; }
		set 
		{
			c_back = value;
			Invalidate();
		}
	}

	/// <summary>
	/// Number of Bars to be drawn
	/// </summary>
	public int numBars
	{
		get {return NumBars; }
		set 
		{
			NumBars = value;
			xBarSize = this.Bounds.Width/NumBars;
			Invalidate();
		}
	}

	/// <summary>
	/// Set the value of the bars to be drawn
	/// </summary>
	/// <param name="spectrum_values">Array of floats, with the values of the bars</param>
	public void SetBarsValue (float[] spectrum_values)
	{
		float constant = (float)this.Bounds.Height/(float)MaxValue;

		for (i=0; i<NumBars; i++)
			spec[i]=(int)((float)spectrum_values[i]*constant);
	}
	protected override void OnPaintBackground(PaintEventArgs e)
	{
		Graphics gxOff; //Offscreen graphics

		gxOff = Graphics.FromImage(bufferBitmap);
		gxOff.FillRectangle(b_back, 0, 0, this.Bounds.Width, this.Bounds.Height);

		xPos=0;
		for (i = 0; i < NumBars; i++)
		{
			height = (int)(spec[i]);
			gxOff.FillRectangle(b_bars, xPos, this.Bounds.Height, xBarSize, -height);
			xPos += xBarSize;			
		}
		e.Graphics.DrawImage(bufferBitmap, 0, 0);//copy back to screen
	}
}

 